package com.flex.reflection.util;

/**
 * @author ganlt
 * @since 2019/09/23 16:00
 */
public class MethodUtils {

    public static boolean isSetter(String method,Class clazz){
        boolean startCheck = method.startsWith("set") ;
        if (!startCheck) {
            return false;
        }

        String name = method.substring(method.indexOf("set") + 3).toLowerCase();
        try {
            clazz.getField(name);
            return true;
        } catch (NoSuchFieldException e) {
            return false;
        }
    }

    public static boolean isGetter(String method,Class clazz){
        boolean startCheck = method.startsWith("get") || method.startsWith("is") ;
        if (!startCheck) {
            return false;
        }

        int index = 0;
        if (method.startsWith("get")) {
            index = method.indexOf("get") + 3;
        } else if (method.startsWith("is")) {
            index = method.indexOf("is") + 2;
        }

        String name = method.substring(index).toLowerCase();
        try {
            clazz.getField(name);
            return true;
        } catch (NoSuchFieldException e) {
            return false;
        }
    }

    public static boolean isPropertyGetter(String property,Class clazz){

        try {
            clazz.getMethod("get"+StringUtils.upperFirstLatter(property));
            return true;
        }  catch (NoSuchMethodException e) {
            try {
                clazz.getMethod("is"+StringUtils.upperFirstLatter(property));
                return true;
            } catch (NoSuchMethodException ex) {
                return false;
            }
        }
    }
}
